import { provide, inject, ref, unref, nextTick } from 'vue'
import { message as Message } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import { nanoid } from 'nanoid'
import { getAllProject, getPrjStatus } from '@/api/catalog.js'
import { resultProps } from 'ant-design-vue/es/result'
import { useDbType } from '@/views/db-management/provide-context.js'

/**
 * Symbol
 */
export const dataSourceSymbol = Symbol('dataSource')
export const loadingSymbol = Symbol('loading')

/**
 * 注册
 */
export function useProvideContextRegistry() {
  let dataSource = ref([])
  let loading = ref(false)
  provide(dataSourceSymbol, dataSource)
  provide(loadingSymbol, loading)
}

/**
 * 获取值
 */
export function useDataSource() {
  return inject(dataSourceSymbol)
}
export function useLoading() {
  return inject(loadingSymbol)
}

/**
 * 管理工具
 */
export function useDataSourceManager() {
  let dataSource = useDataSource()
  let loading = useLoading()
  let dbType = useDbType()

  let update = debounce(async () => {
    loading.value = true
    try {
      console.log(dbType)
      let result = (await getAllProject(dbType)) || {}
      // 手动设置所有项目的虚拟status
      let prjIds = result.data.map(item => item.id)
      let prjStatus = (await getPrjStatus({ prjIds }, dbType)) || {}
      let prjStatusObj = prjStatus.data
      let prjList = result.data
      prjList.forEach(item => {
        item.publishedStatus = prjStatusObj[item.id]
      })
      dataSource.value = prjList
      await nextTick()
      loading.value = false
    } catch (e) {
      Message.error('加载失败')
      loading.value = false
    }
  }, 300)

  return { update }
}
